﻿using ServiceStack.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Top.Common;
using Top.Core;
using Top.Data;
using Top.DataBase;
using Top.DataBase.Model;
using Top.Web.Sync;

namespace TopsNtegratingProcessingWindowsService
{

    //static class Program
    //{
    //    /// <summary>
    //    /// 应用程序的主入口点。
    //    /// </summary>
    //    static void Main()
    //    {
    //        ServiceBase[] ServicesToRun;
    //        ServicesToRun = new ServiceBase[] 
    //        { 
    //            new Service1() 
    //        };
    //        ServiceBase.Run(ServicesToRun);
    //    }
    //}


    static class Program
    {

        private static ConcurrentDictionary<int, T_LuckProduct> luckProductList = new ConcurrentDictionary<int, T_LuckProduct>();
        private const string SingleHost = "8cf5c9b595894d8c.m.cnhza.kvstore.aliyuncs.com";
        //private const string SingleHost = "127.0.0.1";
        private const int RedisPort = 6379;
        private const string RedisPwd = "8cf5c9b595894d8c:Tops4008125121";
        private const string ChannelName = "TopsHandleLuckRecordWindowsService";
        private static string FinanceUrl = TopConfigHelper.GetAppSettings("FinanceUrl");

        private static readonly int totalThreads = 10;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            //RedPacketRequest("14281fc1-fd61-40f1-8408-d6ae67813b29", "18|3361", 300);
            //ThreadPool.SetMaxThreads(10, 10);

            InitLuckProductList();
            RedisSub();
            //ThreadPoolRedisSub();
            //ThreadPoolTest();
            Console.ReadKey();
        }

        public static void ThreadPoolTest()
        {
            ThreadPool.SetMaxThreads(10, 10);
            for (int i = 0; i < 10; i++)
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    //Thread.Sleep(1000);
                    int a, b;
                    ThreadPool.GetAvailableThreads(out a, out b);
                    Console.WriteLine(string.Format("({0}/{1}) #{2} : {3}", a, b, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("mm:ss")));
                    RedisSub();
                });
            }

            var redisConsumer = new RedisClient(SingleHost, RedisPort);
            var msgs = redisConsumer.BRPop(ChannelName, 30);
            //if (msgs==null)
            //{
            //    continue;
            //}
            //string jobMsg = msgs.FirstOrDefault();
           
        }

        public static void ThreadPoolRedisSub()
        {
            try
            {
                using (var redisConsumer = new RedisClient(SingleHost, RedisPort, RedisPwd))
                //using (var redisConsumer = new RedisClient(SingleHost,RedisPort))
                using (var subscription = redisConsumer.CreateSubscription())
                {
                    Console.WriteLine("连接Redis..");
                    
                    subscription.OnMessage = (channel, msg) =>
                    {
                        Console.WriteLine(String.Format("{0}: {1}", channel, msg));
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            RedPacketWork(msg.Split('#')[0], msg.Split('#')[1], msg.Split('#')[2], msg.Split('#')[3]);
                        }
                    };
                    subscription.SubscribeToChannels(ChannelName);
                }

            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
            }
            Console.ReadLine();

        }


        static void UpdateData()
        {
            string conStr = TopConfigHelper.GetConnectionStrings("default");
            string sql1 = @"
select * from dbo.T_LuckRecord where CreateTime>='2015-11-11' and ExchangeKid=0 and IsWin=1
union all
select * from dbo.T_LuckRecord2 where CreateTime>='2015-11-11'and ExchangeKid=0 and IsWin=1
union all
select * from dbo.T_LuckRecord3 where CreateTime>='2015-11-11'and ExchangeKid=0 and IsWin=1
union all
select * from dbo.T_LuckRecord4 where CreateTime>='2015-11-11'and ExchangeKid=0 and IsWin=1
";
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(sql1, con))
                {
                    con.Open();
                    sda.Fill(dt);
                    Console.WriteLine("读取完毕");
                }
            }
            foreach (DataRow item in dt.Rows)
            {
                //Work(item["kid"].ToString(), item["BrokerKid"].ToString(),"50");
            }
        }

        static void RedisSub()
        {
            try
            {
                using (var redisConsumer = new RedisClient(SingleHost, RedisPort, RedisPwd))
                //using (var redisConsumer = new RedisClient(SingleHost,RedisPort))
                using (var subscription = redisConsumer.CreateSubscription())
                {
                    Console.WriteLine("连接Redis..");
                    subscription.OnMessage = (channel, msg) =>
                    {
                        Console.WriteLine(String.Format("{0}: {1}", channel, msg));
                        if (!string.IsNullOrWhiteSpace(msg))
                        {
                            RedPacketWork(msg.Split('#')[0], msg.Split('#')[1], msg.Split('#')[2], msg.Split('#')[3]);
                        }
                    };
                    subscription.SubscribeToChannels(ChannelName);
                }

            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
            }
            Console.ReadLine();
        }

        public static void InitLuckProductList()
        {
            luckProductList.Clear();
            List<T_LuckProduct> productList = new List<T_LuckProduct>();
            string sql = @"select * from t_luckproduct";
            using (var db = new DbTour())
            {
                productList = db.Sql(sql).ToList<T_LuckProduct>().Result;
            }
            foreach (T_LuckProduct item in productList)
            {
                luckProductList.TryAdd(item.Kid, item);
                Console.WriteLine("奖品名称：{0}\t奖品ID:{1}", item.Name, item.Kid);
            }
        }

        //static void Work(string luckRecordKid, string userToken,string turnPoint)
        //{
        //    int userpoint = Convert.ToInt32(turnPoint);

        //    string tokenStr = userToken;
        //    char markchar = Convert.ToChar(tokenStr.Substring(tokenStr.Length - 2, 1));
        //    int mark = (int)markchar;
        //    string tableName = string.Empty;
        //    switch (mark % 4)
        //    {
        //        case 0:
        //            tableName = "T_LuckRecord";
        //            break;
        //        case 1:
        //            tableName = "T_LuckRecord2";
        //            break;
        //        case 2:
        //            tableName = "T_LuckRecord3";
        //            break;
        //        case 3:
        //            tableName = "T_LuckRecord4";
        //            break;
        //        default:
        //            tableName = "T_LuckRecord";
        //            break;
        //    }

        //    using (var db = new DbTour())
        //    {
        //        try
        //        {
        //            #region 根据redis 订阅机制 获取中奖编号处理数据

        //            string sqlLuckRecord = string.Format("select * from {0} where Kid={1}", tableName, luckRecordKid);
        //            T_LuckRecordExpand item = db.Sql(sqlLuckRecord, luckRecordKid).FirstOrDefault<T_LuckRecordExpand>().Result;
        //            if (item == null)
        //            {
        //                ErrorLog.WriteLog(string.Format("纪录编号：{0},提示信息：{1}", luckRecordKid, "该记录不存在"));
        //                return;
        //            }

        //            if (!luckProductList.ContainsKey(Convert.ToInt32(item.LuckProductKid)))
        //            {
        //                ErrorLog.WriteLog(string.Format("拉取抽奖奖品信息失败，无法找到奖品ID:{0}   时间：{1}", item.LuckProductKid,DateTime.Now));
        //                Console.WriteLine("找不到奖品---> 奖品ID:{1}", item.LuckProductKid);
        //                return;
        //            }
        //            T_LuckProduct luckProductModel = luckProductList[Convert.ToInt32(item.LuckProductKid)];

        //            #region 处理业务

        //            //const string sqlLuckProduct = "select * from T_LuckProduct where Kid={0}";
        //            //T_LuckProduct luckProductModel = db.Sql(sqlLuckProduct, item.LuckProductKid).FirstOrDefault<T_LuckProduct>().Result;
        //            //if (luckProductModel == null)
        //            //{
        //            //    ErrorLog.WriteLog(string.Format("拉取抽奖奖品信息失败，无法找到奖品ID:{0}", item.LuckProductKid));
        //            //    return;
        //            //}

        //            //if (luckProductModel.Name == "谢谢参与")
        //            //{
        //            //    ErrorLog.WriteLog(string.Format("纪录编号：{0}，抽中物品名称：{1}，提示信息：{2}", luckRecordKid, luckProductModel.Name, "不扣积分范畴"));
        //            //    return;
        //            //}

        //            //const string sqlExchangeRule = "select * from T_ExchangeRule where F_ProductKid={0}";
        //            //T_ExchangeRule wxchangeRuleModel = db.Sql(sqlExchangeRule, item.LuckProductKid).FirstOrDefault<T_ExchangeRule>().Result;
        //            //if (wxchangeRuleModel == null)
        //            //{
        //            //    wxchangeRuleModel = new T_ExchangeRule()
        //            //    {
        //            //        F_Status = 3
        //            //    };
        //            //}
        //            //if (wxchangeRuleModel == null)
        //            //{
        //            //    ErrorLog.WriteLog(string.Format("兑换规则产品编号：{0},提示信息：{1}", item.LuckProductKid, "该记录不存在"));
        //            //    return;
        //            //}

        //            db.Begin();


        //            //新增兑换记录信息
        //            Guid guid = Guid.NewGuid();
        //            var productsexchange = new T_ProductsExchange_new()
        //            {
        //                F_UserKid = item.BrokerKid,
        //                F_UserToken = item.F_UserToken,
        //                F_ProductKid = item.LuckProductKid ?? 0,
        //                F_ExchangeTime = DateTime.Now,
        //                F_PointNum = userpoint,//抽奖积分
        //                F_IsDisplay = luckProductModel.Point>0 ? 0 : 1,//1显示  0不显示
        //                F_OrderNo = DateTime.Now.ToString("yyyyMMddHHmmfff"),
        //                F_Guid = guid,
        //                F_IsStatus = luckProductModel.Point > 0 ? 10 : 1, //1:审核中 3：兑换成功
        //                F_ExchangeType = "幸运大转盘"
        //            };
        //            int exchangeKid = ProductsExchange_Add(productsexchange, db);
        //            if (exchangeKid <= 0)
        //            {
        //                db.Rollback();
        //                return;
        //            }


        //            //更新中奖纪录中兑换记录编号
        //            if (LuckRecord_Update(exchangeKid, item.Kid, db, tableName,"") <= 0)
        //            {
        //                db.Rollback();
        //                return;
        //            }


        //            //抽奖扣积分
        //            if (UpdateBrokerPoint(item.F_UserToken, -userpoint, "broker.pointluck.cash", exchangeKid, db) <= 0)
        //            {
        //                db.Rollback();
        //                return;
        //            }


        //            //抽中积分奖励
        //            if (luckProductModel.Point > 0)
        //            {
        //                if (UpdateBrokerPoint(item.F_UserToken, luckProductModel.Point, "broker.pointluck.award", exchangeKid, db) <= 0)
        //                {
        //                    db.Rollback();
        //                    return;
        //                }
        //            }

        //            #endregion

        //            db.Commit();
        //            return;

        //            #endregion


        //            #region foreach


        //            //DateTime startDate = DateTime.Now.Date;
        //            //DateTime endDate = startDate.AddDays(1);
        //            //const string sqlLuckRecord = "select * from T_LuckRecord where ExchangeKid=0 and CreateTime>={0} and CreateTime<{1}";
        //            //IList<T_LuckRecord> luckRecordList = db.Sql(sqlLuckRecord, startDate, endDate).ToList<T_LuckRecord>();
        //            //foreach (var item in luckRecordList)
        //            //{
        //            //    #region MyRegion

        //            //    const string sqlLuckProduct = "select * from T_LuckProduct where Kid={0}";
        //            //    T_LuckProduct luckProductModel = db.Sql(sqlLuckProduct, item.LuckProductKid).FirstOrDefault<T_LuckProduct>();

        //            //    if (dicLuckRecordNotDisplay.ContainsKey(luckProductModel.Name))
        //            //    {
        //            //        return;
        //            //    }


        //            //    const string sqlExchangeRule = "select * from T_ExchangeRule where F_ProductKid={0}";
        //            //    T_ExchangeRule wxchangeRuleModel = db.Sql(sqlExchangeRule, item.LuckProductKid).FirstOrDefault<T_ExchangeRule>();

        //            //    db.Begin();


        //            //    //新增兑换记录信息
        //            //    Guid guid = Guid.NewGuid();
        //            //    var productsexchange = new T_ProductsExchange()
        //            //    {
        //            //        F_UserKid = item.BrokerKid,
        //            //        F_ProductKid = item.LuckProductKid ?? 0,
        //            //        F_ExchangeTime = DateTime.Now,
        //            //        F_PointNum = -100,//抽奖积分
        //            //        F_IsDisplay = dicExchangeNotDisplay.ContainsKey(luckProductModel.Name) ? 0 : 1,//1显示  0不显示
        //            //        F_OrderNo = DateTime.Now.ToString("yyyyMMddHHmmfff"),
        //            //        F_Guid = guid,
        //            //        F_IsStatus = dicAutoList.ContainsKey(luckProductModel.Name) ? 10 : (wxchangeRuleModel.F_Status == 1 ? 1 : 3), //1:审核中 3：兑换成功
        //            //        F_ExchangeType = "幸运大转盘"
        //            //    };
        //            //    int exchangeKid = ProductsExchange_Add(productsexchange, db);
        //            //    if (exchangeKid <= 0)
        //            //    {
        //            //        db.Rollback();
        //            //        return;
        //            //    }


        //            //    //更新中奖纪录中兑换记录编号
        //            //    if (LuckRecord_Update(exchangeKid, item.Kid, db) <= 0)
        //            //    {
        //            //        db.Rollback();
        //            //        return;
        //            //    }


        //            //    //抽奖扣积分
        //            //    if (UpdateBrokerPoint(item.BrokerKid, -100, "broker.point.cash", db) <= 0)
        //            //    {
        //            //        db.Rollback();
        //            //        return;
        //            //    }


        //            //    //抽中积分奖励
        //            //    if (luckProductModel.Point > 0)
        //            //    {
        //            //        if (UpdateBrokerPoint(item.BrokerKid, luckProductModel.Point, "broker.pointluck.award", db) <= 0)
        //            //        {
        //            //            db.Rollback();
        //            //            return;
        //            //        }
        //            //    }

        //            //    #endregion

        //            //    db.Commit();
        //            //    return;
        //            //}

        //            #endregion

        //        }
        //        catch (Exception ex)
        //        {
        //            db.Rollback();
        //            ErrorLog.WriteLog(ex);
        //            return;
        //        }
        //    }


        //}


        //static void GoGoGo(string msg)
        //{
        //    ThreadPool.QueueUserWorkItem(o =>
        //    {
        //        RedPacketWork(msg.Split('#')[0], msg.Split('#')[1], msg.Split('#')[2], msg.Split('#')[3]);
        //        //Thread.Sleep(1000);
        //        int a, b;
        //        ThreadPool.GetAvailableThreads(out a, out b);
        //        Console.WriteLine(string.Format("线程池：({0}/{1}) #{2} : {3}", a, b, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString()));
        //    });
        //}

        static void RedPacketWork(string luckRecordKid, string userToken, string turnPoint, string brokerKid)
        {
            int userpoint = Convert.ToInt32(turnPoint);

            string tokenStr = userToken;
            char markchar = Convert.ToChar(tokenStr.Substring(tokenStr.Length - 2, 1));
            int mark = (int)markchar;
            string tableName = string.Empty;
            switch (mark % 4)
            {
                case 0:
                    tableName = "T_LuckRecord";
                    break;
                case 1:
                    tableName = "T_LuckRecord2";
                    break;
                case 2:
                    tableName = "T_LuckRecord3";
                    break;
                case 3:
                    tableName = "T_LuckRecord4";
                    break;
                default:
                    tableName = "T_LuckRecord";
                    break;
            }

            using (var db = new DbTour())
            {
                try
                {
                    #region 根据redis 订阅机制 获取中奖编号处理数据

                    string sqlLuckRecord = string.Format("select * from {0} where 1=1 and exchangekid = 0 and Kid={1}", tableName, luckRecordKid);
                    T_LuckRecordExpand item = db.Sql(sqlLuckRecord, luckRecordKid).FirstOrDefault<T_LuckRecordExpand>().Result;
                    if (item == null)
                    {
                        ErrorLog.WriteLog(string.Format("纪录编号：{0},提示信息：{1}", luckRecordKid, "该记录不存在"));
                        return;
                    }

                    if (!luckProductList.ContainsKey(Convert.ToInt32(item.LuckProductKid)))
                    {
                        ErrorLog.WriteLog(string.Format("拉取抽奖奖品信息失败，无法找到奖品ID:{0}   时间：{1}", item.LuckProductKid, DateTime.Now));
                        Console.WriteLine("找不到奖品---> 奖品ID:{1}", item.LuckProductKid);
                        return;
                    }
                    T_LuckProduct luckProductModel = luckProductList[Convert.ToInt32(item.LuckProductKid)];

                    #region 处理业务

                    db.Begin();

                    Console.WriteLine("请求红包接口...");
                    Stopwatch MyStopWatch = new Stopwatch();
                    MyStopWatch.Start();
                    string orderNo = string.Empty;
                    //请求红包兑换
                    for (int i = 0; i < 3; i++)
                    {
                        orderNo = RedPacketRequest(userToken, brokerKid + "|" + luckRecordKid, luckProductModel.Point);
                        if (!string.IsNullOrWhiteSpace(orderNo))
                        {
                            MyStopWatch.Stop();
                            decimal ts = MyStopWatch.ElapsedMilliseconds;
                            Console.WriteLine("用户：{0}&{1}&{2}\t红包兑换成功\t耗时：{3}毫秒", userToken, brokerKid + "|" + luckRecordKid, luckProductModel.Point, ts);
                            break;
                        }
                        if (i == 2 && string.IsNullOrWhiteSpace(orderNo))
                        {
                            MyStopWatch.Stop();
                            decimal ts = MyStopWatch.ElapsedMilliseconds;
                            Console.WriteLine("用户：{0}&{1}&{2}\t红包兑换失败\t耗时：{3}毫秒", userToken, brokerKid + "|" + luckRecordKid, luckProductModel.Point, ts);
                            return;
                        }
                    }

                    //新增兑换记录信息
                    Guid guid = Guid.NewGuid();
                    var productsexchange = new T_ProductsExchange_new()
                    {
                        F_UserKid = item.BrokerKid,
                        F_UserToken = item.F_UserToken,
                        F_ProductKid = item.LuckProductKid ?? 0,
                        F_ExchangeTime = DateTime.Now,
                        F_PointNum = 0,//抽奖积分
                        F_IsDisplay = 1,//1显示  0不显示
                        F_OrderNo = orderNo,
                        F_Guid = guid,
                        F_IsStatus = 10, //1:审核中 3：兑换成功
                        F_ExchangeType = "幸运大转盘"
                    };
                    int exchangeKid = ProductsExchange_Add(productsexchange, db);
                    if (exchangeKid <= 0)
                    {
                        db.Rollback();
                        return;
                    }

                    //更新中奖纪录中兑换记录编号以及状态
                    if (LuckRecord_Update(exchangeKid, item.Kid, db, tableName, orderNo) <= 0)
                    {
                        db.Rollback();
                        return;
                    }

                    #endregion

                    db.Commit();
                    Console.WriteLine("红包兑换完毕...");
                    return;

                    #endregion

                }
                catch (Exception ex)
                {
                    db.Rollback();
                    ErrorLog.WriteLog(ex);
                    return;
                }
            }


        }

        public static int UpdateBrokerPoint(string userToken, int point, string remark, int exchangeKid, DbTour db)
        {
            var brokerPoint = GetBrokerPoint(userToken, db);
            if (brokerPoint == null) return -1;

            brokerPoint.F_PointBalance += point;
            //TODO 积分更新有问题 待确认
            if (point > 0)
            {
                brokerPoint.F_PointAll += point;
            }
            if (point < 0)
            {
                brokerPoint.F_PointCash += -point;
            }
            PointManager_AddPoint(userToken, point, remark, exchangeKid, db);
            return UpdateField(brokerPoint.Kid, brokerPoint.F_UserToken, brokerPoint.F_PointBalance, brokerPoint.F_PointCash, brokerPoint.F_PointAll, db);

        }

        internal static bool PointManager_AddPoint(string userToken, int point, string remark, int exchangeKid, DbTour db)
        {
            var brokerPoint = PointManager_Get(userToken, db);
            if (brokerPoint == null) return false;

            var pointDetail = new T_PointDetail_new()
            {
                F_AddTime = DateTime.Now,
                F_BuildingKid = 0,
                F_PointCode = remark,
                F_Point = point,
                F_PointSource = 4,
                F_PointId = brokerPoint.Kid,
                F_ProductExchangeKid = exchangeKid
            };

            const string sql =
@"insert into T_PointDetail_new (F_PointId,F_BuildingKid,F_PointCode,F_Point,F_AddTime,F_PointSource,F_ProductExchangeKid)
                values({0:F_PointId},
                {0:F_BuildingKid},
                {0:F_PointCode},
                {0:F_Point},
                {0:F_AddTime},
                {0:F_PointSource},
                {0:F_ProductExchangeKid});
                select LAST_INSERT_ID();";

            return db.Sql(sql, pointDetail).ExecuteScalar<int>().Result > 0;


        }

        public static T_PointMain_new PointManager_Get(string userToken, DbTour db)
        {
            const string sql = @"select * from T_PointMain_new where F_UserToken = {0} limit 1";
            return db.Sql(sql, userToken).FirstOrDefault<T_PointMain_new>().Result;
        }

        private static int UpdateField(int pointMainKid, string userToken, int pointBalance, int pointCash, int pointAll, DbTour db)
        {
            var obj = new
            {
                F_PointBalance = pointBalance,
                F_PointCash = pointCash,
                F_UserToken = userToken,
                F_PointAll = pointAll
            };
            const string sql = @"update T_PointMain_new set F_PointBalance={0:F_PointBalance},F_PointCash={0:F_PointCash},F_PointAll={0:F_PointAll} where F_UserToken={0:F_UserToken}";
            return db.Sql(sql, obj).ExecuteNonQuery().Result;
        }

        public static T_PointMain_new GetBrokerPoint(string userToken, DbTour db)
        {
            const string sql = @"select * from T_PointMain_new where F_UserToken = {0} limit 1";
            T_PointMain_new resultModel = db.Sql(sql, userToken).FirstOrDefault<T_PointMain_new>().Result;
            if (resultModel != null)
            {
                return resultModel;
            }
            return new T_PointMain_new();
        }

        public static int LuckRecord_Update(int exchangeKid, int luckRecordKid, DbTour db, string tableName, string orderno)
        {
            string sql = string.Format("UPDATE {0} set ExchangeKid={1},IsWin=1,OrderNo='{2}' where Kid={3}", tableName, exchangeKid, orderno, luckRecordKid);
            return db.Sql(sql).ExecuteNonQuery().Result;
        }

        public static int ProductsExchange_Add(T_ProductsExchange_new model, DbTour db)
        {
            const string sql = @"insert into T_ProductsExchange_new (F_UserToken,F_ProductKid,F_ExchangeTime,F_PointNum,F_OrderNo,F_Guid,F_IsStatus,F_Remark,F_ExchangeType,F_IsDisplay) 
                values ({0:F_UserToken},
                        {0:F_ProductKid},
                        {0:F_ExchangeTime},
                        {0:F_PointNum},
                        {0:F_OrderNo},
                        {0:F_Guid},
                        {0:F_IsStatus},
                        '',
                        {0:F_ExchangeType},
                        {0:F_IsDisplay});
                select LAST_INSERT_ID();";

            return db.Sql(sql, model).ExecuteScalar<int>().Result;
        }

        public static string RedPacketRequest(string userToken, string outTransactionNumber, double amount)
        {
            //请求红包兑换
            HttpRequest www = new HttpRequest(FinanceUrl);
            www.Path = "/api/transfer/SaveBonus";
            www.FormBody.Add("BrokerUserToken", userToken);
            www.FormBody.Add("OutTransactionNumber", outTransactionNumber);
            www.FormBody.Add("Amount", amount);
            www.Sign();
            try
            {
                //var temp = www.GetString();
                var orderno = www.Kakao<string[]>();
                if (orderno.Code == 0)
                {
                    return orderno.Data[0];
                }
                else
                {

                    ErrorLog.WriteLog("接口错误：\r\n" + www.GetString());
                    return null;
                }

            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
                return null;
            }
        }


        public static async Task<object> DefeatRegain()
        {
            //获取红包发放失败的信息
            string sql = "";
            return null;
        }

        public class T_LuckProduct
        {
            /// <summary>
            /// 奖品id
            /// </summary>
            public int Kid { get; set; }
            /// <summary>
            /// 奖品图片角度
            /// </summary>
            public double Angle { get; set; }
            /// <summary>
            /// 奖品名称
            /// </summary>
            public string Name
            {
                get;
                set;
            }
            /// <summary>
            /// 中奖概率
            /// </summary>
            public double Chance { get; set; }
            /// <summary>
            /// 奖品数量
            /// </summary>
            public int Count { get; set; }
            /// <summary>
            /// 增加积分，实物为0，虚拟为对应的积分
            /// </summary>
            public double Point { get; set; }
            /// <summary>
            /// 中奖描述
            /// </summary>
            public string Description { get; set; }

            /// <summary>
            /// 出奖周期
            /// </summary>
            public int Rate { get; set; }

            /// <summary>
            /// 周期内最大出奖量
            /// </summary>
            public int MaxCount { get; set; }

            /// <summary>
            /// 周期内已出奖数量
            /// </summary>
            public int LuckCount { get; set; }

        }

        public class T_ProductsExchange_new : T_ProductsExchange
        {
            public string F_UserToken { get; set; }
        }

        public class T_LuckRecordExpand : T_LuckRecord
        {
            public string F_UserToken { get; set; }
        }

        public class T_PointMain_new : T_PointMain
        {
            public string F_UserToken { get; set; }
        }

        public class T_PointDetail_new : T_PointDetail
        {
            public int F_ProductExchangeKid { get; set; }
        }
    }

}
